package utility

import (
	"context"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"net/http"
	"websocket/internal/consts"
)

type uCommon struct {
}

var Common = uCommon{}

func (u *uCommon) BuildErr(ctx context.Context, code int, msg ...string) error {
	msgText := ""
	if len(msg) > 0 {
		//手动消息内容优先
		msgText = msg[0]
	} else {
		if code >= http.StatusContinue && code <= http.StatusNetworkAuthenticationRequired {
			//http status错误码
			msgText = consts.StatusHttp().Text(code)
		} else {
			//自定义错误码
			msgText = consts.StatusCustom().Text(code)
		}
	}
	return gerror.NewCode(gcode.New(code, "", nil), msgText)
}

func (u *uCommon) OutputLog2Day(ctx context.Context, v ...interface{}) {
	u.OutputLog2DayByGroup(ctx, "", v...)
}

func (u *uCommon) OutputLog2DayByGroup(ctx context.Context, group string, v ...interface{}) {
	line := garray.New()
	for _, value := range v {
		line.Append("\n")
		line.Append(value)
	}
	logger := g.Log().Cat(gtime.Now().Format("Ymd"))
	if group != "" {
		logger.Cat(group)
	}
	logger.Print(ctx, line.Slice()...)
}

func (u *uCommon) BuildDatetime() string {
	return gtime.Now().Format("Y-m-d H:i:s.u")
}

func (u *uCommon) BuildWebsocketRes(ctx context.Context, work *consts.WebsocketWorkContext) *consts.WebsocketWorkRes {
	res := new(consts.WebsocketWorkRes)
	res.Code = 0
	res.Msg = "ok"
	res.Unique = work.Unique
	return res
}
